package com.example.threadlocaldemo0.service;

import com.example.threadlocaldemo0.dao.AllDao;
import com.example.threadlocaldemo0.utils.ConnectionContainer;
import com.example.threadlocaldemo0.utils.JdbcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;
import java.sql.Connection;

@Service
public class OrderService {

    @Autowired
    private AllDao allDao;

    @Autowired
    private DataSourceTransactionManager transactionManager;

    public void placeOrder(String userId, String commodityCode, Integer count, Integer money) {

        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        // 设置事务名称
        definition.setName("MyTx");

        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // 开启事务
        TransactionStatus transactionStatus = transactionManager.getTransaction(definition);

        try {
            allDao.insertOrder(userId, commodityCode, count, money);
            allDao.updateAccount(userId, money);
            allDao.updateStorage(commodityCode, count);

            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback(transactionStatus);
        }

    }

}